<?php
/**
 * 二维码生成页面
 * 用于生成和下载邀请二维码
 */

session_start();
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/qr_generator.php';

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

// 获取用户信息
try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
    
    if (!$user) {
        header('Location: login.php');
        exit;
    }
} catch (PDOException $e) {
    error_log("获取用户信息失败: " . $e->getMessage());
    header('Location: login.php');
    exit;
}

// 处理下载请求
if (isset($_GET['action']) && $_GET['action'] === 'download') {
    $filename = 'qrcode_' . $user['invite_code'] . '.png';
    $filepath = saveQRCodeToFile($user['invite_code'], $username, $filename);
    
    if (file_exists($filepath)) {
        header('Content-Type: image/png');
        header('Content-Disposition: attachment; filename="邀请二维码_' . $username . '_' . $user['invite_code'] . '.png"');
        header('Content-Length: ' . filesize($filepath));
        readfile($filepath);
        exit;
    }
}

// 处理生成请求
if (isset($_GET['action']) && $_GET['action'] === 'generate') {
    header('Content-Type: image/png');
    $qr_data = generateStyledInviteQRCode($user['invite_code'], $username, 400);
    $data = explode(',', $qr_data)[1];
    echo base64_decode($data);
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生成邀请二维码</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .container {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        h1 {
            color: #333;
            margin-bottom: 30px;
        }
        
        .qr-preview {
            margin: 30px 0;
        }
        
        .qr-image {
            max-width: 400px;
            max-height: 400px;
            border: 3px solid #667eea;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .actions {
            margin: 30px 0;
        }
        
        .btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 8px;
            cursor: pointer;
            margin: 10px;
            font-size: 16px;
            text-decoration: none;
            display: inline-block;
            transition: all 0.3s ease;
        }
        
        .btn:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
        }
        
        .btn.secondary {
            background: #6c757d;
        }
        
        .btn.secondary:hover {
            background: #5a6268;
        }
        
        .info-box {
            background: #e7f3ff;
            border: 1px solid #b3d9ff;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
            text-align: left;
        }
        
        .back-btn {
            background: #6c757d;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin-bottom: 20px;
        }
        
        .back-btn:hover {
            background: #5a6268;
        }
    </style>
</head>
<body>
    <button class="back-btn" onclick="window.history.back()">← 返回</button>
    
    <div class="container">
        <h1>📱 邀请二维码生成器</h1>
        
        <div class="info-box">
            <h3>用户信息</h3>
            <p><strong>用户名：</strong><?php echo htmlspecialchars($username); ?></p>
            <p><strong>邀请码：</strong><?php echo htmlspecialchars($user['invite_code'] ?? '未生成'); ?></p>
            <p><strong>邀请链接：</strong><?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/login.php?invite=' . urlencode($user['invite_code'] ?? ''); ?></p>
        </div>
        
        <div class="qr-preview">
            <img id="qr-image" class="qr-image" 
                 src="generate_qr.php?action=generate&t=<?php echo time(); ?>" 
                 alt="邀请二维码">
        </div>
        
        <div class="actions">
            <a href="generate_qr.php?action=download" class="btn" download>下载二维码</a>
            <button class="btn secondary" onclick="refreshQR()">刷新二维码</button>
            <button class="btn secondary" onclick="copyLink()">复制邀请链接</button>
        </div>
        
        <div class="info-box">
            <h3>使用说明</h3>
            <ul>
                <li>点击"下载二维码"将二维码保存到本地</li>
                <li>可以将二维码分享到微信、QQ等社交平台</li>
                <li>好友扫描二维码后会直接跳转到注册页面</li>
                <li>注册时邀请码会自动填入，建立邀请关系</li>
                <li>好友交易时您将获得40%的手续费分成</li>
            </ul>
        </div>
        
        <div class="info-box">
            <h3>分享建议</h3>
            <ul>
                <li>在微信群、朋友圈分享二维码</li>
                <li>制作海报时嵌入二维码</li>
                <li>通过私聊发送给好友</li>
                <li>在社交媒体平台发布</li>
            </ul>
        </div>
    </div>

    <script>
        // 刷新二维码
        function refreshQR() {
            const qrImage = document.getElementById('qr-image');
            const timestamp = new Date().getTime();
            qrImage.src = 'generate_qr.php?action=generate&t=' + timestamp;
        }
        
        // 复制邀请链接
        function copyLink() {
            const inviteLink = '<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/login.php?invite=' . urlencode($user['invite_code'] ?? ''); ?>';
            
            if (navigator.clipboard) {
                navigator.clipboard.writeText(inviteLink).then(() => {
                    alert('邀请链接已复制到剪贴板！');
                }).catch(() => {
                    fallbackCopy(inviteLink);
                });
            } else {
                fallbackCopy(inviteLink);
            }
        }
        
        // 降级复制方案
        function fallbackCopy(text) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            alert('邀请链接已复制到剪贴板！');
        }
        
        // 自动刷新二维码（每5分钟）
        setInterval(refreshQR, 300000);
    </script>
</body>
</html>
